<template>
  <div class="process">
    <h2>商品信息管理</h2>
    <div class="line-container">
      <div class="box">
        <select class="el-input border" v-model="selectedGoodsBrowse">
          <option value="">日浏览量</option>
          <option value="小于500">500以下</option>
          <option value="500到5000">500到5000</option>
          <option value="大于5000">5000以上</option>
        </select>
        <select class="el-input border" v-model="selectedGoodsEnquire">
          <option value="">近7天询盘数</option>
          <option value="小于50">50以下</option>
          <option value="50到300">50到300</option>
          <option value="大于300">300以上</option>
        </select>
        <select class="el-input border" v-model="selectedGoodsCollect">
          <option value="">近7天收藏量</option>
          <option value="小于50">50以下</option>
          <option value="50到100">50到100</option>
          <option value="大于100">100以上</option>
        </select>
        <select class="el-input border" v-model="selectedGoodsTransaction">
          <option value="">近7天交易数</option>
          <option value="小于50">50以下</option>
          <option value="50到200">50到200</option>
          <option value="大于200">200以上</option>
        </select>
      </div>
      <div class="box">
        <el-input class="el-input" v-model="searchQuery" placeholder="输入商品信息搜索" @keyup.enter="searchUsers"></el-input>
        <select class="el-input border" v-model="selectedCategory">
          <option value="">商品分类</option>
          <option value="食品生鲜">食品生鲜</option>
          <option value="电子产品">电子产品</option>
          <option value="生活用品">生活用品</option>
          <option value="宠物花蕊">宠物花蕊</option>
          <option value="日用洗涤">日用洗涤</option>
          <option value="运动器材">运动器材</option>
          <option value="图书音像">图书音像</option>
          <option value="服装鞋帽">服装鞋帽</option>
          <option value="美容彩妆">美容彩妆</option>
        </select>
        <select class="el-input border" v-model="selectedSeller">
          <option value="">商家名称</option>
             <option v-for="(name, index) in nameGoodsSorts" :key="index" :value="name">{{ name }}</option>
        </select>
        <button class="border button" @click="reset">重置</button>
      </div>
    </div>
    <div class="line-container">
      <h3>商品列表</h3>
      <el-table :data="currentUsers" stripe ref="userTable">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="商品信息" width="150">
          <template slot-scope="scope">
            <img :src="scope.row.GoodsPicture" alt="" style="width: 60px; height: 60px;">
            <div class="right" style="position: absolute;left: 80px;top: 22px;">
              <p>{{ scope.row.GoodsNamegoods }}</p>
              <p>{{ scope.row.GoodsId }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="GoodsSort" label="商品分类"></el-table-column>
        <el-table-column prop="GoodsDescription" label="商品描述" width="170">
          <template slot-scope="scope">
            <div style="padding-right: 5px;">
              <p class="description-ellipsis">{{ scope.row.GoodsDescription }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="GoodsPrice" label="商品价格"></el-table-column>
        <el-table-column label="商家信息" width="100">
          <template slot-scope="scope">
            <div>
              <p>{{ scope.row.UserName }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="GoodsTime" label="上架时间" width="130">
          <template slot-scope="scope">
            <div>
              {{ formatTime(scope.row.GoodsTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="GoodsBrowse" label="日浏览量"></el-table-column>
        <el-table-column prop="GoodsEnquire" label="近7天询盘数"></el-table-column>
        <el-table-column prop="GoodsCollect" label="近7天收藏量"></el-table-column>
        <el-table-column prop="GoodsTransaction" label="近7天交易数" width="80"></el-table-column>
        <el-table-column label="商品状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.GoodsScope" active-color="#13ce66" inactive-color="#ff4949"
              :active-value="'上架中'" :inactive-value="'下架中'" @change="handleGoodsStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <p style="color: blue;cursor: pointer;" @click="showDetailDialog(scope.row)">查看详情</p>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog :visible.sync="dialogVisible" GoodsDescription="商品详情" width="700px">
      <el-form :model="detail" ref="editForm" label-width="200px">
        <div class="detail-row">
          <div>
            <img :src="detail.GoodsPicture" style="border: 1px solid #ccc;width: 200px;height: 200px;" alt="">
          </div>
          <div style="margin-left: 20px;">
            <div class="detail-item">
              <h3>{{ detail.GoodsNamegoods }}</h3>
              <h3 class="detail-label">商品ID：{{ detail.GoodsId }}</h3>
            </div>
            <div class="just" style="justify-content: start; display: flex;">
              <div>
                <div class="detail-item">
                  <p class="detail-label">商家信息
                    <span>{{ detail.UserName }}</span>
                    <span>{{ detail.phone }}</span>
                  </p>
                </div>
                <div class="detail-item">
                  <p class="detail-label">商品价格 <span>{{ detail.GoodsPrice }}</span></p>
                </div>
                <div class="detail-item">
                  <p class="detail-label">商品分类 <span>{{ detail.GoodsSort }}</span></p>
                </div>
                <div class="detail-item">
                  <p class="detail-label">上架时间 <span>
                    {{ formatTime(detail.GoodsTime) }}
                  </span></p>
                </div>
              </div>
              <div>
                <div class="detail-item">
                  <p class="detail-label">日浏览量 <span>{{ detail.GoodsBrowse }}</span></p>
                </div>
                <div class="detail-item">
                  <p class="detail-label">近7天询盘数 <span>{{ detail.GoodsEnquire }}</span></p>
                </div>
                <div class="detail-item">
                  <p class="detail-label">近7天收藏量 <span>{{ detail.GoodsCollect }}</span></p>
                </div>
                <div class="detail-item">
                  <p class="detail-label">近7天交易数 <span>{{ detail.GoodsTransaction }}</span></p>
                </div>
              </div>
            </div>
            <div class="detail-item">
              <p class="detail-label">商品描述</p>
              <span style="display: block; margin-bottom: 10px;">{{ detail.GoodsDescription }}</span>
            </div>

          </div>
        </div>

      </el-form>
      <span>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import jq from "jquery";
import { Message } from 'element-ui';
export default {
  data() {
    return {
      users: [],
      userPhones: {}, // 存储用户ID和电话的映射
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      detail: {},
      dialogVisible: false,
      remark: '',
      selectedCategory: '',
      selectedSeller: '',
      selectedGoodsBrowse: '',
      selectedGoodsEnquire: '',
      selectedGoodsCollect: '',
      selectedGoodsTransaction: '',
      batchStatus: '',
      batchRemark: '',
      selectedUsers: [],
      nameGoodsSorts: [],
      currentIndex: 0,
    };
  },
  mounted() {
    this.fetchData();
    // 移除输入框聚焦时的边框样式
    document.querySelectorAll('.el-input input, .el-input select').forEach(input => {
      input.addEventListener('focus', () => {
        input.style.outline = 'none';
        input.style.borderColor = '#e2e2e2';
      });
    });
  },
  computed: {
    currentUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      let filteredUsers = this.users.filter(user => {
        const isSearchMatch = user.GoodsNamegoods.includes(this.searchQuery) || String(user.GoodsId).includes(this.searchQuery);
        const isCategoryMatch = this.selectedCategory === '' || user.GoodsSort === this.selectedCategory;
        const isSellerMatch = this.selectedSeller === '' || user.UserName === this.selectedSeller;
        const isGoodsBrowseMatch = this.selectedGoodsBrowse === '' || (() => {
          if (this.selectedGoodsBrowse === '小于500') return user.GoodsBrowse < 500;
          if (this.selectedGoodsBrowse === '500到5000') return user.GoodsBrowse >= 500 && user.GoodsBrowse <= 5000;
          if (this.selectedGoodsBrowse === '大于5000') return user.GoodsBrowse > 5000;
          return true;
        })();
        const isGoodsEnquireMatch = this.selectedGoodsEnquire === '' || (() => {
          if (this.selectedGoodsEnquire === '小于50') return user.GoodsEnquire < 50;
          if (this.selectedGoodsEnquire === '50到300') return user.GoodsEnquire >= 50 && user.GoodsEnquire <= 300;
          if (this.selectedGoodsEnquire === '大于300') return user.GoodsEnquire > 300;
          return true;
        })();
        const isGoodsCollectMatch = this.selectedGoodsCollect === '' || (() => {
          if (this.selectedGoodsCollect === '小于50') return user.GoodsCollect < 50;
          if (this.selectedGoodsCollect === '50到100') return user.GoodsCollect >= 50 && user.GoodsCollect <= 100;
          if (this.selectedGoodsCollect === '大于100') return user.GoodsCollect > 100;
          return true;
        })();
        const isGoodsTransactionMatch = this.selectedGoodsTransaction === '' || (() => {
          if (this.selectedGoodsTransaction === '小于50') return user.GoodsTransaction < 50;
          if (this.selectedGoodsTransaction === '50到200') return user.GoodsTransaction >= 50 && user.GoodsTransaction <= 200;
          if (this.selectedGoodsTransaction === '大于200') return user.GoodsTransaction > 200;
          return true;
        })();
        const isGoodsProcessMatch = user.GoodsProcess === '已通过';

        return isSearchMatch && isCategoryMatch && isSellerMatch && isGoodsBrowseMatch && isGoodsEnquireMatch && isGoodsCollectMatch && isGoodsTransactionMatch && isGoodsProcessMatch;
      });
      return filteredUsers.slice(start, end);
    }
  },
  methods: {
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    handleGoodsStatusChange(row) {
      console.log('触发状态变更:', row.GoodsScope);
      this.goodsscope(row.GoodsId, row.GoodsScope)
        .then(res => {
          Message.success(`商品${row.GoodsNamegoods}状态更新成功`);
          console.log('接口返回:', res);
        })
        .catch(err => {
          Message.error(`商品${row.GoodsNamegoods}状态更新失败`);
          console.error('接口错误:', err);
        });
    },
    fetchData() {
      // 先获取用户数据
      this.getUser().then(() => {
        // 再获取商品数据
        this.getData();
      });
    },
    getUser() {
      return new Promise((resolve) => {
        const _this = this;
        jq.ajax({
          type: "get",
          url: "http://127.0.0.1:3000/usermess",
          success(res) {
            if (res.data) {
              res.data.forEach(user => {
                _this.userPhones[user.UserId] = user.phone; // 建立用户ID和电话的映射
              });
            }
            resolve();
          }
        });
      });
    },
    getData() {
      let _this = this;
      jq.ajax({
        type: "get",
        url: "http://127.0.0.1:3000/getShopData",
        success(res) {
          if (res.data) {
            _this.users = res.data.map(goods => ({
              ...goods,
              phone: _this.userPhones[goods.UserId] || ''
              
            }));
            _this.nameGoodsSorts = [...new Set(res.data.map(item => item.UserName))];
            console.log('_this.users', _this.users);
            _this.totalUsers = _this.users.length; // 更新总记录数
          }
        }
      });
    },
    goodsscope(goodsId, GoodsScope) {
      return new Promise((resolve, reject) => {
        jq.ajax({
          type: 'PUT',
          url: 'http://127.0.0.1:3000/goodsscope',
          data: {
            GoodsId: goodsId,
            GoodsScope: GoodsScope
          },
          success(res) {
            console.log('接口响应123:', res);
            if (res.status === 200) {
              resolve(res);
            } else {
              reject(new Error('更新失败'));
            }
          },
          error(err) {
            console.log('网络错误:', err);
            reject(err);
          }
        });
      });
    },

    reset() {
      // 重置所有输入框和选择框的值
      this.searchQuery = '';
      this.selectedCategory = '';
      this.selectedSeller = '';
      this.selectedGoodsBrowse = '';
      this.selectedGoodsEnquire = '';
      this.selectedGoodsCollect = '';
      this.selectedGoodsTransaction = '';

    },
    searchUsers() {
      this.currentPage = 1;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    showDetailDialog(row) {
      console.log("查看详情点击成功");
      // 确保row有值
      if (row) {
        this.detail = row;
        this.dialogVisible = true;
      } else {
        console.error('传递的行数据row未定义');
      }
    },
    confirmEdit() {
      // 这里假设后端接口接收true或false表示商品状态
      const status = this.detail.GoodsScope;
      // 调用后端接口更新商品状态
      // 这里只是示例，实际应根据具体接口情况调整
      console.log('更新商品状态为:', status);
      this.dialogVisible = false;
    },
    updateGoodsStatus(user, status, remark) {
      // 模拟与后端交互更新商品状态
      return new Promise((resolve) => {
        setTimeout(() => {
          // 这里根据实际情况更新user的状态
          user.GoodsScope = status;
          if (status === '不通过') {
            user.processRecord = remark;
          }
          resolve();
        }, 1000);
      });
    },
    confirm() {
      // 这里可以添加确认操作的逻辑，例如调用API保存反馈状态等
      console.log('点击了确认按钮，当前反馈状态：', this.detail.GoodsScope);
      // 假设调用API成功后关闭弹窗
      this.dialogVisible = false;
    },
  },
  created() {
    this.totalUsers = this.users.length;
  }
}
</script>

<style lang="less" scoped>
.process {
  padding: 70px 20px 20px 230px;
  background-color: #F9FAFB;
  width: 100%;

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .line-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    position: relative;
    margin: 20px 10px;
    width: 98%;

    .description-ellipsis {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }


    .box {
      display: flex;
      justify-content: space-evenly;
      width: 90%;
      margin: 10px auto;

      select {
        margin-right: 10px;
      }

      .el-input {
        margin: 10px;
        width: 400px;
        height: 40px;
        color: #5d5a5a;
        font-size: 16px;

        span {
          padding: 10px;
        }

        input {
          padding: 10px 34px;
          border-radius: 5px;
          border: 1px solid #e2e2e2;
          color: #5d5a5a;
        }
      }

      .border {
        border: 1px solid #e2e2e2;
        border-radius: 5px;
        background-color: transparent;
        font-size: 16px;
        padding-left: 20px;

        img {
          position: relative;
          top: 3px;
          right: 2px;
          width: 16px;
          height: 16px;
        }
      }

      .button {
        width: 400px;
        height: 40px;
        margin: 10px;
        border: transparent;
        background-color: #007BFF;
        color: white;
      }

      .color {
        background-color: #1f3ff1;
        color: white;
      }

    }

    h3 {
      display: block;
      padding: 30px 0 20px 20px;
    }
  }

  .pop {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

    p {
      font-size: 17px;
    }
  }

  .detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    width: 100%;
  }

  .detail-main {
    width: 90%;
  }

  .detail-item {
    flex: 1;
    margin-right: 10px;
  }

  .detail-label {
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;

    span {
      color: #5d5a5a;
      margin: 0 10px;
    }
  }

  .close-button {
    background-color: #f4f4f4;
    color: #666;
    border: 1px solid #ccc;
  }

  .send-button {
    background-color: #409eff;
    color: white;
    border: none;
  }

  .confirm-button {
    background-color: #27c24c;
    color: white;
    border: none;
  }

  .stats-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 20px 10px;
  }

  .stat-item {
    width: calc(50% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;

  }

  .stat-item-1 {
    width: calc(25% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .stat-change {
    color: green;
  }

  .increase {
    color: green;
  }

  .decrease {
    color: red;
  }

  .stat-tip {
    color: rgb(255, 115, 0);
  }
}
</style>    